<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>server</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="/css/public.css" media="all">
</head>
<body>
<div class="layuimini-container" id="app">
    <div class="layuimini-main">
        <fieldset class="table-search-fieldset">
            <legend>游戏进度分布</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="" lay-filter="table-search">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary"  lay-submit lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索</button>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">选择区服:</label>
                        <div class="layui-input-inline">
                            <select name="gameArea" class="layui-select" lay-filter="gameArea" v-model="selectedGameArea">
                                <option value="">全部</option>
                                <option v-for="(item,index) in services" :value="item.server_id || item.serverId || item.serverid || item.server || item.id">{{item.name || item.server_name || item.name_cn || ('S'+(item.server_id||item.id))}}</option>
                            </select>
                        </div>
                    </div>


                <br>
                    <div class="layui-inline">
                        <label class="layui-form-label">榜单类型:</label>
                        <div class="layui-input-inline">
                            <select name="type" class="layui-select" >
                                <option value="level">等级分布</option>
                                <option value="tower">爬塔分布</option>
                                <option value="task">主线任务分布</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="layui-inline">
                        <label class="layui-form-label">导出时间:</label>
                        <div class="layui-input-inline">
                            <input type="text" name="exportDate" id="exportDate" placeholder="选择导出日期" class="layui-input" readonly>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>
        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-sm" lay-event="export" id="exportBtn">
                    <i class="layui-icon layui-icon-download-circle"></i> 导出数据
                </button>
            </div>
        </script>
        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>
        <script type="text/html" id="currentTableBar">

        </script>
    </div>
</div>

<script src="/lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script src="/js/common.js?v=5" charset="utf-8"></script>
<script>
    new Vue({
        el: "#app",
        data: {
            services: JSON.parse(localStorage.getItem('services')),
            selectedGameArea: ''
        },
        mounted:function () {
            var vm = this;
            // 默认选中第一个区服
            if (Array.isArray(vm.services) && vm.services.length > 0) {
                var f = vm.services[0];
                vm.selectedGameArea = (f.server_id || f.serverId || f.serverid || f.server || f.id || '') + '';
            }
            layui.use(['form', 'table','laydate'], function () {
                var isLodedTable = false;
                var $ = layui.jquery,
                    form = layui.form,
                    table = layui.table
                    ,laydate=layui.laydate;

                // 动态options后强制渲染select，确保拿到gameArea
                form.render('select');

                // 同步默认值到 DOM 与 Layui
                if (vm.selectedGameArea) {
                    $('select[name="gameArea"]').val(vm.selectedGameArea);
                    form.render('select');
                }

                // 监听选择变化，保持 Vue 与 Layui 同步
                form.on('select(gameArea)', function(data){
                    vm.selectedGameArea = data.value;
                });

                laydate.render({
                    elem: '#createTime0',
                    value: getYmd(0)
                });
                laydate.render({
                    elem: '#createTime1',
                    value: getYmd(1)
                });
                
                // 导出日期选择器
                laydate.render({
                    elem: '#exportDate',
                    type: 'date',
                    value: getYmd(0)
                });

                var getColsByType = function(type){
                    switch(type){
                        case 'level':
                            return [[
                                {type: 'numbers', title: '序号', width: 80},
                                {title: '等级', width: 120, field: 'level'},
                                {title: '人数', width: 120, field: 'count'},
                                {title: '占比(%)', width: 120, field: 'percentage'},
                                {title: '平均滞留时间(天)', width: 180, field: 'avg_stay_time'}
                            ]];
                        case 'tower':
                            return [[
                                {type: 'numbers', title: '序号', width: 80},
                                {title: '爬塔层数', width: 120, field: 'tower_level'},
                                {title: '人数', width: 120, field: 'count'},
                                {title: '占比(%)', width: 120, field: 'percentage'},
                                {title: '平均滞留时间(天)', width: 180, field: 'avg_stay_time'}
                            ]];
                        case 'task':
                            return [[
                                {type: 'numbers', title: '序号', width: 80},
                                {title: '任务ID', width: 100, field: 'task_id'},
                                {title: '任务名称', width: 160, field: 'task_name'},
                                {title: '已接未完成', width: 120, field: 'accept_unfinished'},
                                {title: '未完成占比(%)', width: 130, field: 'accept_unfinished_percent'},
                                {title: '已提交已完成', width: 120, field: 'completed'},
                                {title: '完成占比(%)', width: 120, field: 'completed_percent'},
                                {title: '平均滞留时间(天)', width: 160, field: 'avg_stay_time'}
                            ]];
                 
                        default:
                            return [[
                                {type: 'numbers', title: '序号', width: 80},
                                {title: '等级', width: 120, field: 'level'},
                                {title: '人数', width: 120, field: 'count'},
                                {title: '占比(%)', width: 120, field: 'percentage'},
                                {title: '平均滞留时间(天)', width: 180, field: 'avg_stay_time'}
                            ]];
                    }
                };

                // 检查是否可以导出
                var isExportable = function(type) {
                    return (type === 'level' || type === 'task');
                };

                var loadTable = function(){
                    var currentWhere = form.val('table-search');
                    // 最终以DOM为准，避免被默认值污染
                    var domGA = $('select[name="gameArea"]').val();
                    vm.selectedGameArea = domGA || vm.selectedGameArea || '';
                    currentWhere.gameArea = vm.selectedGameArea;
                    var currentType = currentWhere && currentWhere.type ? currentWhere.type : '';

                    table.render({
                        where: currentWhere,
                        elem: '#currentTableId',
                        url: '/admin/customer/progress',
                        defaultToolbar: ['filter', 'print' ],
                        toolbar: '#toolbarDemo',
                        cols: getColsByType(currentType),
                        limits: [10, 15, 20, 25, 50, 100],
                        limit: 15,
                        page: true,
                        skin: 'line'
                    });
                    isLodedTable = true;
                }

                loadTable();
                // 监听搜索操作
                form.on('submit(data-search-btn)', function (data) {
                    if (!isLodedTable){
                        loadTable();
                    } else {
                        //执行搜索重载，并根据榜单类型切换列
                        var whereObj = form.val('table-search');
                        // 最终以DOM为准，确保取到当前选择
                        var domGA = $('select[name="gameArea"]').val();
                        vm.selectedGameArea = domGA || vm.selectedGameArea || '';
                        whereObj.gameArea = vm.selectedGameArea;
                        var typeVal = whereObj && whereObj.type ? whereObj.type : '';
                        table.reload('currentTableId', {
                            page: { curr: 1 },
                            where: whereObj,
                            cols: getColsByType(typeVal)
                        }, 'data');
                    }
                    return false;
                });


// 监听榜单类型选择变化
                form.on('select(type)', function(data) {
                    // 当类型改变时，更新导出控件的可见性
                    toggleExportControls(data.value);
                });


                // 监听导出按钮点击
                table.on('toolbar(currentTableFilter)', function(obj){
                    var checkStatus = table.checkStatus(obj.config.id);
                    switch(obj.event){
                        case 'export':
                            var currentWhere = form.val('table-search');
                            var domGA = $('select[name="gameArea"]').val();
                            var exportDate = $('input[name="exportDate"]').val();
                            var type = currentWhere && currentWhere.type ? currentWhere.type : '';
                            
                            if (!domGA) {
                                layer.msg('请选择服务器', {icon: 2});
                                return;
                            }
                            
                            if (!exportDate) {
                                layer.msg('请选择导出日期', {icon: 2});
                                return;
                            }
                            
                            if (!isExportable(type)) {
                                layer.msg('只能导出等级分布和主线任务分布数据', {icon: 2});
                                return;
                            }
                            
                            // 构建导出URL
                            var exportUrl = '/admin/customer/exportProgress?' + 
                                'gameArea=' + encodeURIComponent(domGA) + 
                                '&type=' + encodeURIComponent(type) + 
                                '&exportDate=' + encodeURIComponent(exportDate);
                            
                            // 创建隐藏的下载链接
                            var link = document.createElement('a');
                            link.href = exportUrl;
                            link.download = type + '_' + domGA + '_' + exportDate + '.xlsx';
                            document.body.appendChild(link);
                            link.click();
                            document.body.removeChild(link);
                            
                            layer.msg('开始下载...', {icon: 1});
                            break;
                    }
                });

            });
        }
    })

</script>
</body>
</html>